<?php
class ManageItemForm extends Form
{
	function ManageItemForm()
	{
		Form::Form('ManageItemForm');
		
		$censor = Url::get('censor',1);
		
		if($censor == 1 || $censor == 9)
		{
			CGlobal::$website_title = 'Quản trị Sản phẩm';
		}
		elseif($censor==2)
		{
			CGlobal::$website_title = 'Quản trị Sản phẩm ẩn';
		}
		elseif($censor==-1)
		{
			if(!User::have_permit(ADMIN_DEL_ITEM)){
				Url::redirect_current();
			}
			CGlobal::$website_title = 'Quản trị Sản phẩm xoá';
		}

		$this->link_css('style/manage_item.css');
		$this->link_css('style/aznet/ui.datepicker.css');
		$this->link_js('javascript/tooltip.js');
		$this->link_js('javascript/jquery/ui.datepicker.js');
	}

	function delete_multi($item_array)
	{
		if($item_array && is_array($item_array))
		{
			$censor=Url::get('censor',2);

			foreach($item_array as $key=>$item_id){
				if($item_id)
				{
					if($censor==-1 && User::have_permit(ADMIN_DEL_ITEM))
					{
						Item::delete_item_physical($item_id);
					}
					else
					{
						Item::delete_item($item_id);
					}
				}
			}
		}

		Url::redirect_url(Url::build_all(array('selected_ids','cmd','id','product_item')));
	}

	function on_submit()
	{
		if(Url::get('item_update') == 'Cập nhật')
		{
			$name_arr			= $_POST['names'];
			$sku_arr			= $_POST['skus'];
			$offer_arr			= $_POST['offers'];
			$list_brief_arr		= $_POST['list_briefs'];
			$price_arr			= $_POST['prices'];
			$price_out_arr		= $_POST['price_outs'];
			$currency_id_arr	= $_POST['currency_ids'];
			$quantity_arr		= $_POST['quantitys'];
			$item_order_arr		= $_POST['item_orders'];
			$made_in_arr		= $_POST['made_ins'];
			$warranty_arr		= $_POST['warrantys'];
			
			$sql=array();
			
			foreach ($price_arr as $id => $price)
			{
				if(strlen($name_arr[$id])<1)
				{
					$this->setFormError("name".$id,"Tên sản phẩm có mã ".$id." phải có độ dài từ 1 ký tự trở lên !");
					return ;
				}
				
				if(URL::cdouble($price_arr[$id])<0)
				{
					$this->setFormError("price".$id,"Đơn giá sản phẩm có mã ".$id." phải là giá trị >=0 !");
					return ;
				}
				
				if(URL::cdouble($price_out_arr[$id])<0)
				{
					$this->setFormError("price_out".$id,"Giá thị trường sản phẩm có mã ".$id." phải là giá trị >=0 !");
					return ;
				}
				
				$sql[]="UPDATE item SET name='".addslashes($name_arr[$id])."' ,sku='".addslashes($sku_arr[$id])."' ,list_brief='".addslashes($list_brief_arr[$id])."' ,offer='".addslashes($offer_arr[$id])."' ,
										price='".URL::cdouble($price_arr[$id])."' ,price_out='".URL::cdouble($price_out_arr[$id])."', 
										currency_id=".(int)$currency_id_arr[$id]." , quantity=".(int)$quantity_arr[$id]." ,`item_order`='".(int)$item_order_arr[$id]."',`warranty`='".$warranty_arr[$id]."',`made_in`='".$made_in_arr[$id]."' , 
										modify_time=".TIME_NOW.", modify_user_name='".User::user_name()."' WHERE id=".$id;
			}
			
			foreach ($sql as $query)
			{
				DB::query($query,__LINE__.__FILE__);
			}
			
			Url::redirect_url(Url::build_all(array('cmd')));
		}
		
		if(Url::get('cmd')=='move_content')//Chuyển mục
		{
			$str_ids = trim(AZLib::getParam('product_item'),',');
			$catid 	 = (int)Url::get('id_cats',0);

			if($catid!=0 && $str_ids)
			{
				$result = DB::fetch("SELECT parent_id FROM category WHERE id=$catid");
				$parent_id = $result['parent_id'];
				
				
				$l1_id = 0;
				$l2_id = 0;

				if($parent_id)//DM cấp 2 hoặc 3
				{
					$result 	= DB::fetch("SELECT parent_id FROM category WHERE id=$parent_id");
			
					$l1_id = $parent_id;
					$l2_id = $catid;
					
					$sql = 'UPDATE item SET category_id= '.$catid.',level_1_catid = '.$parent_id.' ,level_2_catid = '.$catid.' WHERE id IN('.$str_ids.')';
				}
				else//DM cấp 1
				{
					$l1_id = $catid;
					$l2_id = 0;
						
					$sql = 'UPDATE item SET category_id= '.$catid.',level_1_catid = '.$catid.',level_2_catid = 0 WHERE id IN('.$str_ids.')';
				}
				
				DB::query($sql);

				if(MEMCACHE_ON)
				{
					$arr = explode(',',$str_ids);
					if($arr){
						foreach ($arr as $item_id){
							$item_memcache =  AZMemcache::do_get("item:$item_id");
							if($item_memcache){
								$item_memcache['category_id'] 		= $catid;
								$item_memcache['level_1_catid'] 	= $l1_id;
								$item_memcache['level_2_catid'] 	= $l2_id;
								
								AZMemcache::do_put("item:$item_id",$item_memcache);
							}
						}
					}
				}
			}
			
			Url::redirect_url(Url::build_all(array('cmd')));
		}

		if(Url::get('cmd')=='delete_item')
		{
			if(isset($_REQUEST['selected_ids']))
			{
				$this->delete_multi($_REQUEST['selected_ids']);
			}
			else if(isset($_REQUEST['product_item']))
			{
				$product_item = array(0=>$_REQUEST['product_item']);
				$this->delete_multi($product_item);
			}
		}
	}

	function draw()
	{
		global $display;
		
		AZLib::getCats();

		$this->beginForm(false,'post',false,Url::build_current());

		$created_time_from	= 0;
		$created_time_to	= 0;
		$time_from			= "";
		$time_to			= "";
		$phrase_checked 	= "";
		$free_cat_checked 	= "";
		$up_checked 		= "";
		$pagging 			= "";
		$limit 				= "";
		$lock_checked 		= '';
		$select_subcat_checked = '';

		$items 				= array();

		$id_search 			= (int)Url::get("id_search");
		$censor 			= Url::get("censor",1);		
		
		$user_name 			= AZLib::getParam("user_name");
		$zone_id 			= Url::get("zone_id");
		$searchByCat 		= Url::get("searchByCat");
		$searchByCatType 	= Url::get("searchByCatType",0);
		$searchBySubCat 	= Url::get("searchBySubCat");
		$searchBySubCatType = Url::get("searchBySubCatType",0);
		
		$sort_type 			= Url::get("sort_type",1);
		
		$keywords 			= Url::get("keywords");
		$have_img 			= Url::get("have_img",0);
		$lock_item 			= Url::get("lock");
		$phrase_selected 	= Url::get("phrase");
		$free_cat_selected 	= Url::get("free_cat");
		$up 				= Url::get("up");
		$select_subcat 		= Url::get("select_subcat","");

		$opt_have_img 		= AZLib::getOption(array(0=>"-Tìm theo ảnh-",1=>"-Có ảnh-",2=>"-Không ảnh-"),$have_img);

		if(isset($_REQUEST["created_time"]) && $_REQUEST["created_time"])
		{
			$time_from		= Url::get("created_time");
		}
		
		if(isset($_REQUEST["created_time_to"]) && $_REQUEST["created_time_to"]){
			$time_to		= Url::get("created_time_to");
		}

		if($time_from)
		{
			$date_arr = explode("-",$time_from);
			if(isset($date_arr[0]) && isset($date_arr[1]) && isset($date_arr[2]))
			$created_time_from = mktime(0,0,0,(int)$date_arr[1],(int)$date_arr[0],(int)$date_arr[2]);
		}
		
		if($time_to)
		{
			$date_arr = explode("-",$time_to);
			if(isset($date_arr[0]) && isset($date_arr[1]) && isset($date_arr[2]))
			$created_time_to = mktime(23,59,59,(int)$date_arr[1],(int)$date_arr[0],(int)$date_arr[2]);
		}

		$search_value 	= "";
		$where		 	= "";
		//$order_by   	= "ORDER BY del_time DESC";
		$order_by   	= "";
		$total_item 	= 0;
		
		if($keywords)// neu co search keyword
		{
		 	$search_value 	= ($search_value == ""?" WHERE ":" AND ")."id IN (0)";
		}
		
		if($sort_type == 1)
		{
			$order_by   	= "ORDER BY id DESC";
		}
		elseif($sort_type == 2)
		{
			$order_by   	= "ORDER BY modify_time DESC";
		}
		elseif($sort_type == 3)
		{
			$order_by   	= "ORDER BY item_order ASC";
		}
		
		
		if($free_cat_selected)
		{
			$free_cat_checked = "checked";
			
			$catids = implode(",",array_keys(CGlobal::$allCategories));
			
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "category_id NOT IN($catids)";
			
			$order_by   	= $order_by!=""?$order_by:"ORDER BY id DESC";
		}
		else
		{
			if($searchBySubCat)
			{
				if($searchBySubCatType){// Nếu chỉ tìm trong danh mục con của danh mục cấp 2
					$search_value .= ($search_value == ""?" WHERE ":" AND "). "level_2_catid = ".$searchBySubCat;// Lọc những item có trường level_2_catid là danh mục cấp 2
				}
				else{
					$search_value .= ($search_value == ""?" WHERE ":" AND "). "category_id = ".$searchBySubCat;// Ngược lại, lấy các bản ghi thuộc chính danh mục cấp 2
				}
			}
			elseif($searchByCat)
			{
				// Nếu chỉ tìm trong danh mục con của danh mục cấp 1
				if($searchByCatType){
					// Lọc những item có trường level_1_catid là danh mục cấp 1
					$search_value .= ($search_value == ""?" WHERE ":" AND "). "level_1_catid = ".$searchByCat;
				}
				else{
					// Ngược lại, lấy các bản ghi thuộc chính danh mục cấp 1
					$search_value .= ($search_value == ""?" WHERE ":" AND "). "category_id = ".$searchByCat;
				}
			}
		}
		
		if($censor != 9)
		{
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "status=".$censor;
		}
		
		if($user_name!="")
		{
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "user_name ='$user_name'";
		}
		
		if($select_subcat){				
			$select_subcat_checked = "checked";
		}

		if($up)
		{
			if($created_time_from)
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "created_time >= ".$created_time_from;

			if($created_time_to)
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "created_time <= ".$created_time_to;
			$up_checked = "checked";
		}
		else
		{
			if($created_time_from)
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "modify_time >= ".$created_time_from;

			if($created_time_to)
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "modify_time <= ".$created_time_to;
		}

		if($have_img==1){//có ảnh
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "have_image=1";
		}
		elseif($have_img==2){//ko có ảnh
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "have_image=0";
		}
		
		if($id_search){//ID sản phẩm
			$search_value .= ($search_value == ""?" WHERE ":" AND "). "id=$id_search";
		}
		
		if(Url::get("up"))
			$order_by   	= $order_by!=""?$order_by:"ORDER BY created_time DESC";
		else
			$order_by   	= $order_by!=""?$order_by:"ORDER BY modify_time DESC";
        
		$sql      	= "SELECT * FROM item $search_value $order_by";
		$sql_count	= "SELECT count(*) AS total_row FROM item $search_value";
		
		$total_item	= (int)DB::fetch($sql_count,"total_row");

		if($total_item)
		{
			$pagging=AZPagging::pagingSE($limit,$total_item,50,10,'page_no',true,'Sản phẩm','Trang');
			$sql      .=$limit;
		}

		$re=DB::query($sql);

		if($re)
		{
			$index_temp = 0;
			
			while ($item = mysql_fetch_assoc($re))
			{
				//trạng thái sản phẩm:
				if($item['status']==-1)//Sản phẩm xóa
				{
					$item['bgcolor']="bgcolor=\"#FF6633\"";
				}
				elseif($index_temp)
				{
					$item['bgcolor']="bgcolor=\"#EFEFEF\"";
				}
				else{
					$item['bgcolor']="";
				}

				$index_temp=1-$index_temp;

				$item['created_time']	= 'Đăng: <b>'.date("d/m/Y H:i",$item['created_time']).'</b>';

				if($item['del_time'] && $item['del_user'] && $item['status'] == -1)
				{
					$item['del_time'] = '<br /><font color=red>Xoá: <b>' . date("d/m/Y H:i",$item['del_time']).'</font></b> ( <a target="_blank" href="'.WEB_DIR.$item['del_user'].'"><strong>'.$item['del_user'].'</strong></a>)';

				}
				else{
					$item['del_time']	= '';
				}

				if($item['modify_user_name'] && $item['status'] !=-1 )
				{
					$item['is_modify']	= '<br><font color=gray>Sửa: <b>'.date("d/m/Y H:i",$item['modify_time']).'</font></b>';
					$item['is_modify']	.= ' ( <a target="_blank" href="'.WEB_DIR.$item['modify_user_name'].'"><strong>'.$item['modify_user_name'].'</strong></a>)';
				}
				else{
					$item['is_modify']	= '';
				}

				$item['name']			= AZLib::filter_title($item['name']);
				$item['description']	= AZLib::remove_4_js(AZLib::plainText($item['description']));

				$item['price']				=  number_format($item['price'],0,',','.');
				$item['price_out']			=  number_format($item['price_out'],0,',','.');
				$item['currency_option']	=  AZLib::getOption(array(1=>"VNĐ",2=>"$"),$item['currency_id']);
				
				
				//$item['price']	=  "Giá bán: ".AZLib::priceFomart($item['price'],$item['currency_id']);
				//$item['price_out']	=  "<br /><font color='#999999'>Giá TT: ".AZLib::priceFomart($item['price_out'],$item['currency_id']).'</font>';

				if($item['level_1_catid'] >0)
				{
					if(isset(CGlobal::$allCategories[$item['level_1_catid']]))
						$item['cat_name']		= '<b>'.CGlobal::$allCategories[$item['level_1_catid']]['name'].' ('.$item['level_1_catid'].')</b>';
					else
					{
						$item['cat_name']		= '<b><font color=red>('.$item['level_1_catid'].')</font></b>';
					}

					if(($item['category_id'] >0 && $item['category_id']!=$item['level_1_catid']) || $item['cat_name']=='')
					{

						if(isset(CGlobal::$allCategories[$item['category_id']]))
							$item['cat_name']		.= ' - <i>'.CGlobal::$allCategories[$item['category_id']]['name'].' ('.$item['category_id'].')</i>';
						else
							$item['cat_name']		.= ' - <i><b><font color=red>('.$item['category_id'].')</font></b></i>';
					}
				}

				if($item['img_url']){
					$item['image_src'] 	= 'http://'.CGlobal::$img_server[$item['img_server']].$item['img_url'];
					$item['image'] 		= AZLib::getImageThumb($item['img_url'],110,0,1,$item["img_server"]);
				}
				else
				{
					$item['image_src']	='';
					$item['image']		='';
				}

				$item['href'] = WEB_DIR.AZRewrite::formatUrl('?page=item_detail&id='.$item['id'].'&ebname='.AZLib::safe_title($item['name']));

				$item['edit']		= Url::build('post_item',array('cmd'=>'edit','id'=>$item['id']));

				if($item['status']==-1)
				{
					$item['del_link']		= Url::build_all(array('cmd','id'),'cmd=del_forever&id='.$item['id']);

					$item['re_post']		= Url::build_all(array('cmd','id'),'cmd=re_post&id='.$item['id']);
				}
				elseif($item['status'] == 2 )
				{
					$item['del_link']		= Url::build_all(array('cmd','id'),'cmd=delete&id='.$item['id']);
					
					$item['show_link']		= Url::build_all(array('cmd','id'),'cmd=show&id='.$item['id']);
				}
				else
				{
					$item['del_link']		= Url::build_all(array('cmd','id'),'cmd=delete&id='.$item['id']);
					
					$item['hide_link']		= Url::build_all(array('cmd','id'),'cmd=hide&id='.$item['id']);
				}

				$item['del_cache']		= Url::build_all(array('cmd','id'),'cmd=del_cache&id='.$item['id']);
				
				$items[$item['id']]=$item;
			}
		}

		$display->add('items',$items);

		$type_arr=array(1=>"-Sản phẩm không ẩn-",2=>"-Sản phẩm ẩn-");

		if(User::have_permit(ADMIN_DEL_ITEM))
		{
			$type_arr[-1]="-Sản phẩm đã xoá-";
			$type_arr[9]="-Tất cả các sản phẩm (Cả sản phẩm xóa)-";
		}
		
		$option_censor=AZLib::getOption($type_arr,Url::get('censor',1));

		$display->add('censor',$censor);
		$display->add('option_censor',$option_censor);
		$display->add('have_img_option',$opt_have_img);
		$display->add('lock_checked',$lock_checked);
		$display->add('user_name',$user_name);
		$display->add('created_time',	$time_from);
		$display->add('created_time_to',$time_to);
		$display->add('phrase_checked', $phrase_checked);
		$display->add('free_cat_checked',$free_cat_checked);
		$display->add('up_checked',$up_checked);
		$display->add('select_subcat_checked',$select_subcat_checked);
		$display->add('id_search',$id_search);
		
		$item_cat_search = 	$this->GetCatTree();

		$display->add('list_top_cat_js',AZLib::getOption(AZLib::getTopCats(),999999999));
		$display->add('IS_ADMIN',User::is_admin());
		$display->add('page_no',Url::get('page_no'));

		$display->add('paging',$pagging);
		$display->add('total_item',$total_item);
		
		$display->add('item_cat',AZLib::getOption($this->getOtionCats(),Url::get('id_cats')));
		
		$display->add('category_tree',	json_encode($item_cat_search));
		
		$display->add('catSelected',Url::get('searchByCat',0));
		$display->add('catSelectedType',Url::get('searchByCatType',0));
		$display->add('subCatSelected',Url::get('searchBySubCat',0));
		$display->add('subCatSelectedType',Url::get('searchBySubCatType',0));
		
		$display->add('keywords',$keywords);
		$display->add('sort_type',$sort_type);
		$display->output('ManageItem');
		$this->endForm();				
	}
	
	function GetCatTree($availCat=0)
	{
		$categories = AZLib::getCategoriesTree(1);
		
		if($availCat)
		{
			$returnCat = array();
			foreach($categories as $cat)
			{
				if(strpos(','.$availCat.',',','.$cat['id'].',') !== false)
				{
					$returnCat[$cat['id']] = $cat;
				}
			}
			$categories = $returnCat;
		}
		
		return $categories;
	}

	function getOtionCats($mod_cat_id=0){
		AZLib::getCats();
		foreach(CGlobal::$allCategories as $cat){
			if($mod_cat_id){
				$arr_mod_cat_id = split(",",$mod_cat_id);
				if($cat['parent_id'] && in_array($cat['id'],$arr_mod_cat_id)){
					$subCategories[$cat['parent_id']][$cat['id']] = $cat;
				}
				elseif(!isset($subCategories[$cat['id']]) && in_array($cat['id'],$arr_mod_cat_id)){
					$subCategories[$cat['id']] = array();
				}
				
				if(in_array($cat['id'],$arr_mod_cat_id)){
					$allCategories[$cat['id']] = $cat;
				}
				else{
					$allCategories[$cat['id']] = array();
				}
			}
			else{
				if($cat['parent_id']){
					$subCategories[$cat['parent_id']][$cat['id']] = $cat;
				}
				elseif(!isset($subCategories[$cat['id']])){
					$subCategories[$cat['id']] = array();
				}
				$allCategories[$cat['id']] = $cat;
			}			
		}

		$arr=array();

		if($subCategories){
			foreach ($subCategories as $pid=>$subCats){
				if(isset($allCategories[$pid])){
					$arr[$pid]=$allCategories[$pid]['name'];
				}

				if((isset($allCategories[$pid])) && $subCats){
					foreach ($subCats as $sid=>$subCat){
						$arr[$sid]='-----'.$subCat['name'];
					}
				}
			}
		}

		return $arr;
	}
}
?>